package sf.database.jdbc.lob;

import sf.tools.IOUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.SQLException;

/**
 * 如果数据已经是byte[],请使用javax.sql.rowset.serial.SerialBlob
 */
public class SimpleBlob implements Blob, Serializable {

    private static final long serialVersionUID = 4192412466410263969L;

    protected File file;

    public SimpleBlob() {
    }

    /**
     * 如果数据已经是byte[],请使用javax.sql.rowset.serial.SerialBlob
     */
    public SimpleBlob(File f) {
        this.file = f;
    }

    public long length() throws SQLException {
        return file.length();
    }

    public byte[] getBytes(long pos, int length) throws SQLException {
        if (pos == 1 && length == length())
            try {
                return IOUtils.toByteArray(getBinaryStream());
            } catch (IOException e) {
            }
        throw new RuntimeException("Not implement yet!");
    }

    public InputStream getBinaryStream() throws SQLException {
        try {
            return new BufferedInputStream(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public long position(byte[] pattern, long start) throws SQLException {
        throw new RuntimeException("Not implement yet!");
    }

    public long position(Blob pattern, long start) throws SQLException {
        throw new RuntimeException("Not implement yet!");
    }

    public int setBytes(long pos, byte[] bytes) throws SQLException {
        throw new RuntimeException("Not implement yet!");
    }

    public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException {
        throw new RuntimeException("Not implement yet!");
    }

    public OutputStream setBinaryStream(long pos) throws SQLException {
        throw new RuntimeException("Not implement yet!");
    }

    public void truncate(long len) throws SQLException {
        try {
            IOUtils.saveAsFile(file, new byte[]{});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void free() throws SQLException {
        if (file.exists()) {
            file.delete();
        }
    }

    public InputStream getBinaryStream(long pos, long length) throws SQLException {
        throw new RuntimeException("Not implement yet!");
    }

    public void setFile(File file) {
        this.file = file;
    }
}
